﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;
using RBS.Common;
using RBS.Core.Extension;
using RBS.Web.API.Models;
using JsonData = RBS.Common.JsonEntity.JsonData;

namespace RBS.Web.API.Areas.Deed.Controllers
{
    /// <summary>
    /// 消费券
    /// </summary>
    public class CouponsController : ApiController
    {
        // GET api/coupons
       /* public String Get()
        {
            return "hehe";
        }*/
        private ApiContext db = new ApiContext();
        /// <summary>
        /// 获取消费券
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="type"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public JsonData Get(int uid, int hotelid=0, int type = 1, int page = 0, int limit = 5)
        {
             //new RBS.Core.BLL.P_Advertis_Payment().GetListByUser()
            var jsonData=new JsonData();
            try
            {
                 var bll = new RBS.Core.BLL.P_Advertis_Payment();
                 string strWhere = " and DeedType=  " + type + " and U_Id=" + uid;
                if (hotelid!= 0)
                {
                    strWhere += " and HotelId=" + hotelid;
                } 
                const string orderby = " id  desc";
                var startIndex = page+1; 
                int totalItems = 0; //要分页的总记录数
                DataTable dt = bll.GetListByUser(limit, startIndex, strWhere, orderby, out totalItems).Tables[0]; 
                if (dt.Rows.Count == 0)
                {
                    jsonData.Success = true;
                    jsonData.Data = null;
                    jsonData.PageSize = limit;
                    jsonData.Page = startIndex;
                    jsonData.TotalPage = totalItems;
                    jsonData.Error = "暂无数据";
                    return jsonData;
                } 
                  IList<object> list = new List<object>();
                  foreach (DataRow row in dt.Rows)
                  {
                      list.Add(new
                      {
                          Id=row["id"],
                          batchId = row["batchId"],
                          DeedType = row["DeedType"],
                          Denomination = row["Denomination"],
                          HotelName = new RBS.Core.BLL.Hotel.H_Hotels().GetModelByCache(Convert.ToInt32(row["HotelId"])).H_Name,
                          DeedStatus = GetDeedStatus(Convert.ToInt32(row["DeedStatus"])),
                          UseRules = row["UseRules"],
                          Crowd = row["Crowd"]
                      });
                  } 
                jsonData.Success = true;
                jsonData.Data = list;
                jsonData.PageSize = limit;
                jsonData.Page = startIndex;
                jsonData.TotalPage = totalItems; 
            }
            catch (Exception ex)
            {

                jsonData.Success = false ;
                jsonData.Data = null;
                jsonData.PageSize = limit;
                jsonData.Page = 0;
                jsonData.TotalPage = 0;
                jsonData.Error =ex.Message;
            }
            return jsonData; 
        } 
        public JsonData Post([FromBody]OrderDeed value)
        { 
            var jsonData = new JsonData{Success = true};
            try
            {
               /* foreach (var item in value.Deed)
                {
                    db.OrderUser.Add(item);
                    db.SaveChanges();
                }*/

                //积分
                if (value.Integration != 0 && value.Integration > 0)
                {
                    var model = new RBS.Core.Model.P_Order_User
                        {
                            OrderId = value.OrderId,
                            UId = value.Uid,
                            DeeId = 0,
                            DeedType = "0",
                            CreateDate = DateTime.Now,
                            DeedNum = value.Integration
                        };
                    db.OrderUser.Add(model);
                    db.SaveChanges();
                }
                if (value.CouponsId != "0" && value.CouponsId.Trim().Length>0)
                {
                    var couponsIds = value.CouponsId.Split(','); 
                    foreach (var couponsId in couponsIds)
                    {
                        var bll = new RBS.Core.BLL.V_Deed();
                        var deed = bll.GetModel(Convert.ToInt32(couponsId));
                        var model = new RBS.Core.Model.P_Order_User
                        {
                            OrderId = value.OrderId,
                            UId = value.Uid,
                            DeeId = deed.Batchid,
                            DeedType = deed.DeedType.ToString(),
                            CreateDate = DateTime.Now,
                            DeedNum = deed.Denomination
                        };
                        model = db.OrderUser.Add(model);
                        db.SaveChanges();

                        bll.UpdateBatchStateToLooked(deed.Batchid);
                        //RBSEnums.DeedStatus.Looked 
                    } 
                     
                } 
            }
            catch
            {
                jsonData.Success = false;
                jsonData.Error = "未知错误";
            }
            return jsonData;
        } 
        
        //优惠券状态
        private string GetDeedStatus(int status)
        {
            var str = "";
            Type t = typeof(RBS.Common.RBSEnums.DeedStatus);
            var arrays = Enum.GetValues(t);
            for (int i = 0; i < arrays.LongLength; i++)
            {
                var test = (RBS.Common.RBSEnums.DeedStatus)arrays.GetValue(i);

                if ((int)test != status) continue;

                FieldInfo fieldInfo = test.GetType().GetField(test.ToString());
                object[] attribArray = fieldInfo.GetCustomAttributes(false);
                var attrib = (EnumDescriptionAttribute)attribArray[0];
                str = attrib.Description;
            }
            return str;
        }
    }
}
